package com.headingdata.d2_polymorphism;

public class Test {

    public static void main(String[] args) {
        //目标：多态的好处
        // 好处1：在多态的形式下，右边对象是解耦合的，更便于扩展和维护 可以随意换对象

        People p1 = new Student();
        People p2 = new Teacher();
        People p3 = new People();
        p1.run();//编译看左边，执行看右边
        p2.run();
        Student s1 = (Student) p1;
//        Student s2 = (Student) p2;// 报classCastException  类型转换异常

        System.out.println(p1.name);
        System.out.println(p2.name);
        System.out.println(p3.name);

        //好处2： 定义方法时，使用父类类型的形参，可以接收一切子类对象，扩展性更强，更便利
        Student s = new Student();
        Teacher t = new Teacher();
        test(s);
        test(p3);
        test(t);

    }
    public static void test(People p){
        p.run();
        if(p instanceof Student){
            ((Student) p).test();
        }else if(p instanceof Teacher){
            Teacher t = (Teacher) p;
            t.teacher();
        }

        System.out.println(p.name);
    }
}
